<template>
  <div>
    <!-- 引入全局组件 -->
    <Category :scene="scene"></Category>
    <!-- 平台属性 -->
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <!-- 平台属性页面 -->
      <div v-show="scene == 0">
        <el-button type="primary" size="default" :icon="Plus" @click="addAttr"
          >添加属性</el-button
        >
        <el-table :data="attrList" border style="margin: 20px 0">
          <el-table-column
            label="序号"
            width="80px"
            type="index"
            align="center"
          >
          </el-table-column>
          <el-table-column label="品牌属性" prop="attrName"> </el-table-column>
          <el-table-column label="属性值">
            <template #="{ row, $index }">
              <el-tag
                type="success"
                size="normal"
                v-for="(attrVal, index) in row.attrValueList"
                :key="attrVal.id"
                >{{ attrVal.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #="{ row, $index }">
              <!-- 添加 -->
              <el-button type="primary" size="small" :icon="Edit" @click="updateAttr(row)"></el-button>
              <!-- 删除 -->
              <el-button type="danger" size="small" :icon="Delete" @click="deleteAttr(row)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 平台属性值页面 -->
      <div v-show="scene == 1">
        <el-form :inline="true" size="normal">
          <el-form-item label="属性名">
            <el-input
              placeholder="请输入属性的名字"
              v-model="attrParams.attrName"
              clearable
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          size="default"
          :icon="Plus"
          :disabled="attrParams.attrName ? false : true"
          @click="addAttrValue"
          >添加属性值</el-button
        >
        <el-button @click="cancel">取消</el-button>
        <el-table
          border
          stripe
          style="margin: 20px 0"
          :data="attrParams.attrValueList"
        >
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="80px"
          >
          </el-table-column>
          <el-table-column label="属性值名称">
            <template #="{ row, $index }">
              <el-input
                :ref="(vc) => (inputArr[$index] = vc)"
                v-model="row.valueName"
                placeholder="请输入属性值"
                size="small"
                clearable
                v-if="row.flag"
                @blur="toLook(row, $index)"
                >{{ row.valueName }}</el-input
              >
              <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #="{ row, $index }">
              <el-button
                type="danger"
                size="small"
                :icon="Delete"
                @click="attrParams.attrValueList.splice($index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          size="default"
          :disabled="attrParams.attrValueList.length > 0 ? false : true"
          @click="saveAttr"
          >保存</el-button
        >
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
// 引入icon图标
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
  Plus,
} from "@element-plus/icons-vue";
// 引入仓库
import useCategoryStore from "@/stores/category";
import {
  reqAddOrUpdateAttr,
  reqAttrList,
  reqDeleteAttr,
} from "@/api/product/attr/attr";
import { watch, ref, reactive, nextTick, onUnmounted } from "vue";
import { ElMessage } from "element-plus";
let categoryStore = useCategoryStore();
let scene = ref(0);
let attrList = ref([]);
let inputArr = ref([]);
watch(
  () => categoryStore.c3Id,
  () => {
    getAttrList();
  }
);
const getAttrList = async () => {
  let result = await reqAttrList(
    categoryStore.c1Id,
    categoryStore.c2Id,
    categoryStore.c3Id
  );
  console.log(result);
  attrList.value = result;
};
// 定义需要向服务器传递的数据
let attrParams = reactive({
  attrName: "", //属性名
  attrValueList: [], //属性值
  categoryId: "", //三级目录中的id
  categoryLevel: 3, //三级目录
});
// 添加属性按钮
const addAttr = () => {
  scene.value = 1;
  Object.assign(attrParams, {
    attrName: "", //属性名
    attrValueList: [], //属性值
    categoryId: categoryStore.c3Id, //三级目录中的id
    categoryLevel: 3, //三级目录
  });
};

// 添加属性值按钮
const addAttrValue = () => {
  attrParams.attrValueList.push({
    valueName: "",
    flag: true,
  });
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus();
  });
};

// 编辑页面切换到查看页面
const toLook = (row, $index) => {
  // 属性值不能为空
  if (row.valueName.trim() == "") {
    ElMessage({
      type: "warning",
      message: "属性值不能为空",
    });
    attrParams.attrValueList.splice($index, 1);
    return;
  }
  // 属性值不能重复
  let repeated = attrParams.attrValueList.find((item) => {
    if (row != item) {
      return row.valueName == item.valueName;
    }
  });
  if (repeated) {
    ElMessage({
      type: "warning",
      message: "属性值不能重复",
    });
    attrParams.attrValueList.splice($index, 1);
    return;
  }
  row.flag = false;
};

// 查看页面
const toEdit = (row, $index) => {
  row.flag = true;
  nextTick(() => {
    inputArr.value[$index].focus();
  });
};

// 点击取消
const cancel = () => {
  scene.value = 0;
};

const saveAttr = async () => {
  // 整理参数
  attrParams.attrValueList.forEach((item) => {
    if (item.hasOwnProperty("flag")) {
      delete item.flag;
    }
  });
  try {
    await reqAddOrUpdateAttr(attrParams);
    ElMessage({
      type: "success",
      message: "操作成功",
    });
    scene.value = 0;
    getAttrList();
  } catch (error) {
    ElMessage({
      type: "error",
      message: "操作失败",
    });
  }
};

// 引入lodash的深拷贝
import _ from 'lodash'
// 点击场景一修改按钮的回调
const updateAttr = (row)=>{
  // 切换场景二
  scene.value = 1
  // 深拷贝数据
  Object.assign(attrParams,_.cloneDeep(row))
}

// 点击场景一删除按钮的回调
const deleteAttr = async(row)=>{
  try {
    await reqDeleteAttr(row.id)
    ElMessage({
      type: "success",
      message: "操作成功",
      duration:500
    });
    getAttrList()
  } catch (error) {
    ElMessage({
      type: "error",
      message: "操作失败",
      duration:500
    });
  }
}

// 组件卸载时清除仓库中的数据
onUnmounted(()=>{
  categoryStore.c1Id = ''
  categoryStore.c2Id = ''
  categoryStore.c3Id = ''
  categoryStore.c1List = []
  categoryStore.c2List = []
  categoryStore.c3List = []
})
</script>

<style scoped>
</style>